import 'dart:io' as io;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/providers/gallery_provider.dart';
import 'package:geomancy/providers/system_provider.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/routes/index.dart';
import 'package:geomancy/tools/ad.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/localstorage.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';


void main() {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => SystemProvider()),
        ChangeNotifierProvider(create: (context) => UserProvider()),
        ChangeNotifierProvider(create: (context) => GalleryProvider()),
      ],
      child: const MyApp(),
    )
  );
  if (io.Platform.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  late Future<bool> _firstInstallAppFuture;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 添加观察者监听
    //判断用户是否第一次安装APP，如果是则弹出用户隐私权限的弹窗
    _firstInstallAppFuture = firstInstallAppHandle();
    ///进入APP立刻获取本地存储数据
    LocalStorage.getLocalData(context);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      AdUtil.registerADSDK();
    });

  }

  Future<bool> firstInstallAppHandle() async {
    final systemProvider =  context.read<SystemProvider>();
    LocalStorage prefs = await LocalStorage.getInstance();
    final String? flag = prefs.getString(Constant.FIRSTINSTALLAPP);
    systemProvider.setIsFirstInstallApp = FirstInstallAppExtension.fromString(flag);
    // if (flag == '0') {
    //   await registerADSDK();
    // }
    return flag == '0' ? true : false;
  }


  @override
  Widget build(BuildContext context) {
    final isFirstInstallApp = context.watch<SystemProvider>().getIsFirstInstallApp;
    print('isFirstInstallApp==$isFirstInstallApp');
    return FutureBuilder(
        future: _firstInstallAppFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return const SizedBox.shrink();
          } else {
            return ScreenUtilInit(
              designSize: const Size(750, 1334),
              minTextAdapt: true,
              splitScreenMode: true,
              builder: (context , child) {
                return MaterialApp.router(
                  debugShowCheckedModeBanner: false,
                  localizationsDelegates: const [
                    RefreshLocalizations.delegate,
                    GlobalWidgetsLocalizations.delegate,
                    GlobalMaterialLocalizations.delegate,
                    GlobalCupertinoLocalizations.delegate,
                  ],
                  supportedLocales: const [
                    Locale('zh', 'CH'),
                    Locale('en', 'US'), // English
                  ],
                  locale: const Locale('zh'),
                  title: '入口',
                  theme: ThemeData(
                      primarySwatch: Colors.blue,
                      textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp),
                      appBarTheme: const AppBarTheme(
                          surfaceTintColor: Colors.transparent
                      )
                  ),
                  routerConfig: isFirstInstallApp == FirstInstallApp.no ? AppRouter.routers : AppRouter.firstInstallRouters,
                  // routerConfig: isFirstInstallApp == '0' ? AppRouter.routers : AppRouter.routers,
                  builder: EasyLoading.init(
                    builder: (context, widget) {
                      return MediaQuery(
                        data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
                        child: widget!
                      );
                    }
                  ),
                );
              },
            );
          }
        }
    );
  }
}